package com.zhuozhou.jdyc.main.user.viewmodel;

import android.app.Activity;
import android.app.Application;
import android.app.KeyguardManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.hardware.fingerprint.FingerprintManagerCompat;

import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.zhuozhou.jdyc.R;
import com.zhuozhou.jdyc.api.ConstantsHelper;
import com.zhuozhou.jdyc.base.BaseViewModel;
import com.zhuozhou.jdyc.main.main.activity.TechnicalSupportActivity;
import com.zhuozhou.jdyc.main.user.activity.FeedBackActivity;
import com.zhuozhou.jdyc.main.user.activity.LoginActivity;
import com.zhuozhou.jdyc.util.cache.GlideCacheUtil;
import com.zhuozhou.jdyc.util.log.ToastUtils;
import com.zhuozhou.jdyc.util.update.UpdateManger;
import com.zhuozhou.jdyc.wight.dialog.ConfirmDialog;

import java.io.File;

/**
 * Create by CherishTang on 2020/3/26 0026
 * describe:
 */
public class SettingViewModel extends BaseViewModel {

    public SettingViewModel(@NonNull Application application) {
        super(application);
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.setting_exit) {
            LoginActivity.show(view.getContext(), new Bundle());
        } else if (id == R.id.feedBack) {
            FeedBackActivity.show(view.getContext());
        } else if (id == R.id.versionName) {
            baseView.showLoading("正在检测新版本...");
            new Handler().postDelayed(() -> {
                ConstantsHelper.isSuccessRequestUpdate = true;
                UpdateManger.getInstance().checkUpdateInfo((Activity) view.getContext(),
                        "http://softfile.3g.qq.com:8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk",
                        "1、修复已知bug",
                        "1.0.1");
                baseView.hideLoading();
            }, 2000);
        } else if (id == R.id.cleanUp) {
            TextView tvCleanUp = (TextView) view;
            new ConfirmDialog(view.getContext())
                    .setMessage("是否确定清理缓存")
                    .setOnSureClickListener(dialog -> {
                        try {
                            clearCache();
                            tvCleanUp.setText(getCacheSize());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    })
                    .builder()
                    .show();
        } else if (id == R.id.aboutUs) {
            ToastUtils.showShort(view.getContext(), "请登录官方网站进行查看");
        } else if (id == R.id.tv_support) {
            TechnicalSupportActivity.show(view.getContext(), new Bundle());
        }
    }

    /**
     * 计算缓存大小
     */
    public String getCacheSize() {
        String size = null;
        try {
            long cacheSize = GlideCacheUtil.getInstance().getFolderSize(
                    new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                            + File.separator + ConstantsHelper.ROOTFILEPATH));
            cacheSize += GlideCacheUtil.getInstance().getFolderSize(
                    new File(getApplication().getCacheDir() + File.separator +
                            InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR));
            cacheSize += GlideCacheUtil.getInstance().getFolderSize(getApplication().getCacheDir());
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                cacheSize += GlideCacheUtil.getInstance().getFolderSize(getApplication().getExternalCacheDir());
            }
            size = GlideCacheUtil.getFormatSize(cacheSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 清理缓存
     */
    public void clearCache() {
        GlideCacheUtil.getInstance().clearImageAllCache(getApplication());
        GlideCacheUtil.getInstance().deleteFolderFile(Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + ConstantsHelper.ROOTFILEPATH, false);
        GlideCacheUtil.getInstance().deleteFolderFile(getApplication().getCacheDir().getAbsolutePath(), false);
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            GlideCacheUtil.getInstance().deleteFolderFile(getApplication().getExternalCacheDir().getAbsolutePath(), false);
        }
    }

//    private void showFingerDialog(String message) {
//        new ConfirmDialog(getApplication())
//                .setMessage(message)
//                .setShowCancelView(false)
//                .setOnSureClickListener(v -> {
//                    if (AppSettingHelper.getFingerIsOpen()) {
//                        AppSettingHelper.setFingerIsOpen(false);
//                    } else {
//                        AppSettingHelper.setFingerIsOpen(true);
//                    }
//                }).builder().show();
//    }
//
//    private void showSureDialog(String message) {
//        new ConfirmDialog(getApplication())
//                .setMessage(message)
//                .setShowCancelView(false)
//                .setOnSureClickListener(v -> {
//                    if (AppSettingHelper.getGesturesIsOpen()) {
//                        AppSettingHelper.setGesturesIsOpen(false);
//                        AppSettingHelper.setGestures(null);
//                    } else {
//                        Intent intent = new Intent(getApplication(), LockViewActivity.class);
//                        intent.putExtra("isSet", true);
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//                        LockViewActivity.show(getApplication().,new Bundle());
//                    }
//                    binding.fingerprintPassword.setChecked(AppSettingHelper.getGesturesIsOpen());
//                }).builder().show();
//    }
//
    /**
     * 判断是否支持指纹识别
     */
    public boolean supportFingerprint() {
        if (Build.VERSION.SDK_INT < 23) {
            Toast.makeText(getApplication(), "您的手机不支持指纹解锁哦", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            KeyguardManager keyguardManager = getApplication().getSystemService(KeyguardManager.class);
            FingerprintManagerCompat fingerprintManager = FingerprintManagerCompat.from(getApplication());
            if (!fingerprintManager.isHardwareDetected()) {
                Toast.makeText(getApplication(), "系统不支持指纹功能", Toast.LENGTH_SHORT).show();
                return false;
            } else if (keyguardManager != null && !keyguardManager.isKeyguardSecure()) {
                Toast.makeText(getApplication(), "请先设置锁屏并添加一个指纹", Toast.LENGTH_SHORT).show();
                return false;
            } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                Toast.makeText(getApplication(), "至少在系统中添加一个指纹", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

}
